using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using _404park.Core.Crawler;

namespace _404park.ApplicationServices.Crawler.Parser.Provider
{
	public class YoutubeParser : BaseFeedParser
	{
		public override string BaseUrl { get { return "http://gdata.youtube.com/feeds/api/videos?orderby=relevance&max-results=10&v=2&q={0}&start-index={1}"; } }

        internal override string GetFeedUrl(string keyword, int start = 0)
        {
            return string.Format(BaseUrl, keyword, start*10 + 1);
        }

		internal protected override IList<Feed> ParseFeed(string responseData)
		{
			IList<Feed> feedList = null;

			XmlReader xmlReader = XmlReader.Create(new StringReader(responseData));
			while (xmlReader.Read())
			{
				if ((xmlReader.NodeType == XmlNodeType.Element)
				    && (xmlReader.Name == "entry"))
				{
					string title = string.Empty;
					string description = string.Empty;
					string displayurl = string.Empty;
					string clickurl = string.Empty;


					bool moreRecords = false;
					do
					{
						moreRecords = xmlReader.Read();
						switch (xmlReader.Name)
						{
							case "title":
						{
							title = xmlReader.ReadString();
							break;
						}
							case "media:description":
						{
							description = xmlReader.ReadString();
							break;
						}
							case "media:thumbnail":
						{
							if(xmlReader.GetAttribute("yt:name").Equals("default"))
								displayurl = xmlReader.GetAttribute("url");
							break;
						}
							case "media:player":
						{
							clickurl = xmlReader.GetAttribute("url");
							break;
						}
						}
					} while (moreRecords && xmlReader.Name != "entry");

					if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(clickurl))
					{
						if (feedList == null)
							feedList = new List<Feed>();
						feedList.Add(new Feed { Title = title, Description = description, DisplayUrl = displayurl, ClickUrl = clickurl });
					}
				}

			}
			return feedList;
		}
	}
}

